const express = require("express");
const fs = require("fs");
const path = require("path");
const multer = require("multer");
const BannerModel = require("../models/banners");
const router = express.Router();
const upload = multer({ dest: "uploads" });

/**
 * 新增一个轮播图
 */
router.post("/banners", upload.single("file"), async (req, res) => {
  // 1. 获取前端传递过来的参数
  const file = req.file;
  const { name, startTime, endTime } = req.body;
  console.log(file);
  // 2. 对上传过来的图片文件做一个处理
  const fileData = fs.readFileSync(file.path);
  const filename = `${file.filename}.${file.originalname.split(".")[1]}`;
  const newFilePath = path.resolve(__dirname, "../public", filename);
  fs.writeFileSync(newFilePath, fileData);
  // 3. 写入数据库
  const newBanner = new BannerModel({
    name,
    imgUrl: `http://localhost:3000/${filename}`,
    startTime,
    endTime
  });

  const data = await newBanner.save();

  res.send({
    code: 0,
    msg: "新增成功",
    data
  });
});

/**
 * 获取全部轮播图数据
 */
router.get("/banners", async (req, res) => {
  // 1. 获取前端传递过来的参数
  let page = parseInt(req.query.page) || 1;
  let limit = parseInt(req.query.limit) || 5;

  // 2. 轮播图的总记录条数
  let total = await BannerModel.find().countDocuments();

  // 2. 查询
  const banners = await BannerModel.find()
    .skip((page - 1) * limit)
    .limit(limit)
    .sort({ createdAt: -1 });

  // 3. 响应
  res.send({
    code: 0,
    msg: "查询成功",
    data: {
      banners,
      total
    }
  });
});

/**
 * 删除指定id的轮播图数据
 */
router.delete("/banners/:id", async (req, res) => {
  // 1. 获取id
  const { id } = req.params;

  // 2. 操作数据库
  await BannerModel.deleteOne({ _id: id });

  res.send({
    code: 0,
    msg: "删除成功"
  });
});

/**
 * 修改指定id的轮播图数据
 */
router.patch("/banners/:id", async (req, res) => {
  // 1. 得到id
  const { id } = req.params;
  // 2. 获取修改的数据 req.body

  // 3. 修改
  await BannerModel.updateOne({ _id: id }, req.body);

  res.send({
    code: 0,
    msg: "修改成功"
  });
});

module.exports = router;
